<script lang="ts" setup name="XtxNumbox">
import { getCurrentInstance } from 'vue'
// #1 根据外界的 v-model 绑定的值，展示数据
const props = defineProps({
  modelValue: {
    type: Number,
    default: 1,
  },
  min: {
    type: Number,
    default: 1,
  },
  max: {
    type: Number,
    default: 10,
  },
})
const proxy = getCurrentInstance()?.proxy
const emits = defineEmits<{
  (e: 'update:modelValue', num: number): void
}>()
// #2 进行加减
const decrement = () => {
  if (props.modelValue <= props.min) return
  emits('update:modelValue', props.modelValue - 1)
}
const increment = () => {
  if (props.modelValue >= props.max) return
  emits('update:modelValue', props.modelValue + 1)
}

// #3 输入数据离开的时候也能改变
const handleChange = (e: Event) => {
  // 目标断言 +值转成数字，转出来的结果可能有两种，一种是数字，另一种是 NaN
  let num = +(e.target as HTMLInputElement).value
  // 如果输入的不是数字(NaN)，就把 value 变成默认的 1
  if (isNaN(num)) num = 1
  // 如果输入的小于最小值，就变成最小值
  if (num <= props.min) num = props.min
  if (num >= props.max) num = props.max
  // 更新父亲 v-model 绑定的数据
  emits('update:modelValue', num)
  // 强制更新
  proxy?.$forceUpdate()
}
</script>
<template>
  <div class="xtx-numbox">
    <div class="label">数量</div>
    <div class="numbox">
      <a href="javascript:;" @click="decrement">-</a>
      <input type="text" :value="modelValue" @change="handleChange" />
      <a href="javascript:;" @click="increment">+</a>
    </div>
  </div>
</template>
<style scoped lang="less">
.xtx-numbox {
  display: flex;
  align-items: center;
  .label {
    width: 60px;
    color: #999;
    padding-left: 10px;
  }
  .numbox {
    width: 120px;
    height: 30px;
    border: 1px solid #e4e4e4;
    display: flex;
    > a {
      width: 29px;
      line-height: 28px;
      text-align: center;
      background: #f8f8f8;
      font-size: 16px;
      color: #666;
      &:first-of-type {
        border-right: 1px solid #e4e4e4;
      }
      &:last-of-type {
        border-left: 1px solid #e4e4e4;
      }
    }
    > input {
      width: 60px;
      padding: 0 5px;
      text-align: center;
      color: #666;
    }
  }
}
</style>
